const express = require('express')
const path = require('path')
const http = require('http')
const https = require('https')
const fs = require('fs')
const {
    Server
} = require('socket.io')
// const log4js = require("log4js");
// const logger = log4js.getLogger();

// express
const app = express()
const port = 801;
const port_ssl = 4431;

// 创建http服务器
const server_http = http.createServer(app);
server_http.listen(port, () => {
    console.log('HTTP server is run on port: ' + port);
})

//创建https服务器
var privateKey = fs.readFileSync(path.join(__dirname, '/cert/key.pem'), 'utf8');
var certificate = fs.readFileSync(path.join(__dirname, '/cert/cert.pem'), 'utf8');
var option = {
    key: privateKey,
    cert: certificate
};
const server_https = https.createServer(option, app);
server_https.listen(port_ssl, () => {
    console.log('HTTPS server is run on port: ' + port_ssl);
})

app.use('/static', express.static(path.join(__dirname, 'public')))

app.get('/', (req, res) => {
    res.writeHead(200);
    if (req.protocol === 'https') {
        res.end('Welcome to HTTPS!');
    } else {
        res.end('HTTP!');
    }
})


const USERCOUNT = 3;
// socket.io
const io = new Server(server_https,{
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    }
})
// socket.io链接事件
io.on('connection', (socket) => {

    // 断开链接
    socket.on('disconnect', () => {
        console.log('user disconnected');
    });

    // 加入房间
    socket.on('join',(roomid,user) => {
        socket.join(roomid);
        var myRoom = socket.rooms
        console.log('the user number of room is: ' + myRoom.size);
        if(myRoom.size < USERCOUNT){

        }
        // 只有发送消息的人能收到
        // socket.emit('message',msg)

        // 除自己外，给该房间内所有人
        // Sets a modifier for a subsequent event emission that the event data will only be broadcast to every sockets but the sender.
        socket.to(roomid).emit('joined',user,socket.id)

        // 给某个房间内所有人发消息
        // io.in(roomid).emit('message', msg);

        // 除自己外，给整个站点的所有人发
        // socket.broadcast.emit('message',msg)
    })

    // 接收消息
    socket.on('message', (roomid,msg,user) => {
        // 只有发送消息的人能收到
        // socket.emit('message',msg)

        // 除自己外，给该房间内所有人
        // Sets a modifier for a subsequent event emission that the event data will only be broadcast to every sockets but the sender.
        socket.to(roomid).emit('message',msg,user)

        // 给某个房间内所有人发消息
        // io.in(roomid).emit('message', msg);

        // 除自己外，给整个站点的所有人发
        // socket.broadcast.emit('message',msg)
    });

    // 离开房间
    socket.on('leave', (room)=>{

    })
});